package com.woniuxy.school.dietary.comment.service.impl;

import com.woniuxy.commons.core.exception.SchoolException;
import com.woniuxy.commons.core.model.Result;
import com.woniuxy.school.dietary.comment.entity.CommentInfo;
import com.woniuxy.school.dietary.comment.mapper.CommentInfoMapper;
import com.woniuxy.school.dietary.comment.model.from.AddCommentFrom;
import com.woniuxy.school.dietary.comment.model.from.ReplyCommentFrom;
import com.woniuxy.school.dietary.comment.service.CommentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.school.dietary.comment.util.OSSUtil;
import com.woniuxy.school.dietary.order.client.OrderClient;
import com.woniuxy.school.dietary.order.entity.DietOrder;
import com.woniuxy.school.dietary.store.client.StoreClient;
import com.woniuxy.school.dietary.store.model.dto.FindStoreDto;
import com.woniuxy.school.dietary.store.model.from.FindStoreFrom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年05月14日
 */
@Service
@Slf4j
public class CommentInfoServiceImpl extends ServiceImpl<CommentInfoMapper, CommentInfo> implements CommentInfoService {
   @Resource
   private CommentInfoMapper  commentInfoMapper;
   @Resource
   private StoreClient storeClient;
   @Resource
   private OrderClient orderClient;
    @Override
    public void commentInfoService(AddCommentFrom from,Long userId) throws Exception {
        //判断商家合理性
        //判断订单合理性
        //判断本次评价是否上传了图片file
        //如果存在
        //判断上传的文件类型的合理性
        //合理就执行添加评论操作
        //如果不存在
        //执行添加评论操作
        // 1. 参数非空校验
        if (from == null || from.getStoreId() == null || from.getOrderNum() == null) {
            throw new SchoolException(400, "请求参数不完整");
        }
        if (userId == null) {
            throw new SchoolException(400, "用户未登录");
        }
        // 1. 校验商家是否存在
        FindStoreFrom storeFrom = new FindStoreFrom();
        storeFrom.setStoreId(from.getStoreId());
        Result<FindStoreDto> store = storeClient.findStore(storeFrom);
        if (store.getCode()!=200) throw new SchoolException(store.getCode(),store.getMessage());
        if (store.getData()==null) throw new SchoolException(404,"商家信息有误");
        if (store.getData().getStatus()!=1) throw new SchoolException(500,"商家已禁用");
        if (store.getData().getStoreStatus()!=1) throw new SchoolException(500,"商家正在歇业中");
        FindStoreDto data1 = store.getData();//商家信息

        // 2. 校验订单是否合法（属于当前用户）
        Result<DietOrder> order = orderClient.findOrderByOrderNum(from.getOrderNum());
        if (order.getCode()!=200) throw new SchoolException(order.getCode(),order.getMessage());
        if (order.getData()==null) throw new SchoolException(404,"订单信息有误");
        DietOrder data = order.getData();
        if (!data.getOrderUser().equals(userId)) throw new SchoolException(500,"订单不属于当前用户");
        if (data.getState()!=4) throw new SchoolException(500,"订单还未结束");

        MultipartFile file = from.getFile();
        String userImgs = null;
        Integer pictureFlag = 0;

        // 3. 如果上传了文件，则进行图片类型判断并上传
        if (file != null && !file.isEmpty()) {
            try {
                byte[] header = new byte[4];
                InputStream inputStream = file.getInputStream();
                inputStream.read(header);

                // 判断是否为图片
                if (!OSSUtil.isPic(header)) {
                    throw new IllegalArgumentException("上传的文件不是支持的图片格式");
                }

                // 将流重置以便后续读取
                inputStream.reset();

                // 上传到阿里云 OSS
                String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                userImgs = OSSUtil.uploadFile(inputStream, fileName, "your-bucket-name"); // 替换为你的 bucket 名称
                pictureFlag = 1;

            } catch (IOException e) {
                throw new SchoolException(10007,"文件读取失败");
            }
        }

        // 4. 构建评论实体
        CommentInfo comment = new CommentInfo();
        BeanUtils.copyProperties(comment, from); // 注意顺序
        comment.setId(null); // 插入新数据，避免覆盖
        comment.setPictureFlag(pictureFlag);
        comment.setUserImgs(userImgs);
        comment.setDate(LocalDateTime.now());
        comment.setDeleteFlag(0); // 默认正常
        comment.setReplayFlag(0); // 默认未回复
        // 5. 保存评论
        int insert = commentInfoMapper.insert(comment);
        if (insert <= 0) throw new SchoolException(500,"添加评论失败");
        log.info("用户 {} 成功对商家 {} 的订单 {} 进行了评价", userId, from.getStoreId(), from.getOrderNum());
    }

    @Override

    public void replyComment(ReplyCommentFrom from, Long storeId) {
    //判断评论是否存在
        CommentInfo comment = commentInfoMapper.selectById(from.getCommentId());
        if (comment == null) throw new SchoolException(404,"评论不存在");
        if (comment.getStoreId() != storeId) throw new SchoolException(405,"该评论不属于该商家");
//        // 4. 判断是否已回复过，避免重复回复
//        if (comment.getReplayFlag() != null && comment.getReplayFlag() == 1) {
//            throw new SchoolException(409, "该评论已被回复，请勿重复操作");
//        }
        // 更新评论的回复内容及回复时间
        comment.setReplay(from.getContent());
        comment.setReplyDate(LocalDateTime.now());
        comment.setReplayFlag(1); // 设置为已回复状态
        // 更新数据库
        int rowsAffected = commentInfoMapper.updateById(comment);
        if (rowsAffected != 1) {
            throw new SchoolException(500, "回复失败，请稍后再试");
        }
        log.info("商家回复用户评论成功，评论编号: {}", from.getCommentId());
    }
}

